import type { HttpContext } from '@adonisjs/core/http'
import type { NextFn } from '@adonisjs/core/types/http'

/**
 * Auth middleware is used authenticate HTTP requests and deny
 * access to unauthenticated users.
 */
export default class AuthMiddleware {
  whiteList = ['/auth/login', '/auth/logout']

  async handle({ request, auth }: HttpContext, next: NextFn) {
    const routePath = request.url()
    if (this.whiteList.includes(routePath)) {
      return next()
    }

    await auth.use(auth.defaultGuard).authenticate()
    global.user = auth.user

    return next()
  }
}
